import { IPSDEListDataItem, IPSDEMobMDCtrl } from '@ibiz/dynamic-model-api';
import { DataTypes, ModelTool } from '../../util';

export class AppMobMDCtrlModel {
  /**
   * 多数据部件实例对象
   *
   * @type {IPSDEMobMDCtrl}
   * @memberof AppMobMDCtrlModel
   */
  private MDCtrlInstance!: IPSDEMobMDCtrl;

  /**
   * 构造多数据部件模型
   *
   * @memberof AppMobMDCtrlModel
   */
  constructor(opts?: any) {
    this.MDCtrlInstance = opts as IPSDEMobMDCtrl;
  }

  /**
   * 获取数据项集合
   *
   * @memberof AppMobMDCtrlModel
   */
  public getDataItems() {
    const modelArray: any[] = [
      // 前端新增修改标识，新增为"0",修改为"1"或未设值
      {
        name: 'srffrontuf',
        prop: 'srffrontuf',
        dataType: 'TEXT',
      },
    ];
    if (this.MDCtrlInstance.getPSDEListDataItems()) {
      this.MDCtrlInstance.getPSDEListDataItems()?.forEach((dataitem: IPSDEListDataItem) => {
        const obj: any = {};
        obj.name = dataitem.name.toLowerCase();
        // 附加属性
        const field = dataitem.getPSAppDEField();
        if (dataitem.customCode) {
          obj.customCode = true;
          obj.scriptCode = dataitem.scriptCode;
        } else {
          if (field) {
            obj.prop = field.codeName.toLowerCase();
            obj.dataType = DataTypes.toString(field.stdDataType);
          }
        }
        modelArray.push(obj);
      });

      // 附加界面主键
      const appDataEntity = this.MDCtrlInstance.getPSAppDataEntity();
      const keyField = ModelTool.getAppEntityKeyField(appDataEntity);
      const flag = this.MDCtrlInstance.getPSDEListDataItems()?.find((item: IPSDEListDataItem) => {
        return (
          item.getPSAppDEField && item.getPSAppDEField()?.codeName.toLowerCase() == keyField?.codeName.toLowerCase()
        );
      });
      if (flag) {
        modelArray.push({
          name: appDataEntity?.codeName.toLowerCase(),
          prop: keyField?.codeName.toLowerCase(),
          dataType: 'FRONTKEY',
        });
      }
    }
    return modelArray;
  }
}
